package oprecocerto.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oprecocerto.commom.Util;
import oprecocerto.entity.Acessorio;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class AcessorioServlet extends BaseServlet {

	private static final Logger logger = Logger
			.getLogger(AcessorioServlet.class.getCanonicalName());

	/**
	 * Get the requested entities in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		super.doGet(req, resp);
		logger.log(Level.WARNING, "Obtendo lista de acessorios");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		Iterable<Entity> entities = null;
		if (searchFor == null || searchFor.equals("")) {
			entities = Acessorio.getAllAcessorio();
			out.println(Util.writeJSON(entities));
		} else {
			entities = Acessorio.getAcessorio(searchFor);
			out.println(Util.writeJSON(entities));
		}
		return;
	}

	/**
	 * Insert the new entity
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.WARNING, "Criando Acessorio");
		String nome = req.getParameter("nome");
		String valor = req.getParameter("valor");
		Acessorio.createOrUpdateAcessorio(nome, valor);
	}

	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String nomeAcessorio = req.getParameter("id");
		logger.log(Level.WARNING, "Deletando Acesso {0}", nomeAcessorio);
		Key key = KeyFactory.createKey("Acessorio", nomeAcessorio);
		try {
			Util.deleteFromCache(key);
			Util.deleteEntity(key);
		} catch (Exception e) {
			String msg = Util.getErrorResponse(e);
			resp.getWriter().print(msg);
		}
	}

	/**
	 * Redirect the call to doDelete or doPut method
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}
}
